<?php

namespace App\Http\Controllers\Sdk;

use App\Events\RefreshUserInfo;
use App\Http\Controllers\Controller;
use App\Models\AgentRevenue;
use App\Models\AgentSdkBalanceOperation;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class WalletController extends Controller
{
    /**
     * SDK 转入
     * @param Request $request
     * @return \Dingo\Api\Http\Response
     * @throws \Illuminate\Validation\ValidationException
     */
    public function transfersBalance(Request $request)
    {
        $this->validate($request, [
            'amount' => ['required', 'integer', 'min:1', ],
            'origin_numbering' => ['required', 'unique:agent_sdk_balance_operations,origin_numbering', ],
        ], [
            'amount.required' => '缺失转入金额',
            'amount.integer' => '转入金额不合法',
            'amount.min' => '转入金额最少一分钱',
            'origin_numbering.required' => '缺失渠道订单号',
            'origin_numbering.unique' => '渠道订单号重复',
        ]);

        \DB::transaction(function () use ($request) {
            $amount = $request->get('amount');

            // sdk 余额操作记录
            $sdkOperation = AgentSdkBalanceOperation::query()->create([
                'agent_id' => \Auth::id(),
                'channel_id' => AgentSdkBalanceOperation::CHANNEL_SOLITAIRE,
                'amount' => $amount,
                'numbering' => Carbon::now()->format('ymdHisu') . random_int(0, 9), // 同商品下单订单号生成逻辑一样
                'origin_numbering' => $request->get('origin_numbering')
            ]);

            // 增加余额 和 创建流水
            $this->user->incrementOrDecrementBalance($amount, AgentRevenue::TYPE_SDK_SOLITAIRE_TRANSFER_IN, $sdkOperation);
        });

        // 通知客户端刷新信息
        event(new RefreshUserInfo(\Auth::id()));

        return $this->response->noContent();
    }

    /**
     * 余额操作详情
     * @param Request $request
     * @return mixed
     */
    public function transfersInfo(Request $request)
    {
        try {
            $originNumbering = $request->get('origin_numbering');
            if (empty($originNumbering)) {
                abort(400, '订单不存在');
            }

            $order = AgentSdkBalanceOperation::query()
                ->where('agent_id', \Auth::id())
                ->where('origin_numbering', $originNumbering)
                ->firstOrFail()
                ->toArray();
        } catch (ModelNotFoundException $e) {
            abort(400, '订单不存在');
        }

        return $this->response->array($order);
    }
}
